package com.cocoiko.tools.twitter;

import oauth.signpost.OAuth;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

import com.cocoiko.R;
import com.cocoiko.Setting;
import com.cocoiko.utils.CocoikoConstains;

public class RequestOAuthTwitter extends Activity {
	static final String TAG = "RequestOAuthTwitter";

	private OAuthConsumer consumer;
	private OAuthProvider provider;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		try {
			consumer = new CommonsHttpOAuthConsumer(CocoikoConstains.CONSUMER_KEY,
					CocoikoConstains.CONSUMER_SECRET);
			provider = new CommonsHttpOAuthProvider(
					CocoikoConstains.REQUEST_TOKEN_URL, CocoikoConstains.ACCESS_TOKEN_URL,
					CocoikoConstains.AUTHORIZE_URL);
		} catch (Exception e) {
			// TODO: handle exception
			Log.i(TAG, e.getMessage());
		}
		Log.i(TAG, "Starting task to retrieve request token.");
		new OAuthRequestTokenTask(this, consumer, provider).execute();

	}

	@Override
	protected void onNewIntent(Intent intent) {
		// TODO Auto-generated method stub
		super.onNewIntent(intent);
		SharedPreferences prefs = getSharedPreferences(
				CocoikoConstains.SHARE_PREFER_NAME, MODE_PRIVATE);
		Uri uri = intent.getData();
		if (uri != null) {
			new RetrieveAccessTokenTask(this, consumer, provider, prefs)
					.execute(uri);
			finish();
		}

	}

	public class RetrieveAccessTokenTask extends AsyncTask<Uri, Void, Void> {

		private Context context;
		private OAuthProvider provider;
		private OAuthConsumer consumer;
		private SharedPreferences prefs;

		public RetrieveAccessTokenTask(Context context, OAuthConsumer consumer,
				OAuthProvider provider, SharedPreferences prefs) {
			this.context = context;
			this.consumer = consumer;
			this.provider = provider;
			this.prefs = prefs;
		}

		/**
		 * Retrieve the oauth_verifier, and store the oauth and
		 * oauth_token_secret for future API calls.
		 */
		@Override
		protected Void doInBackground(Uri... params) {
			final Uri uri = params[0];
			final String oauth_verifier = uri
					.getQueryParameter(OAuth.OAUTH_VERIFIER);

			try {
				provider.retrieveAccessToken(consumer, oauth_verifier);

				final Editor edit = prefs.edit();
				edit.putString(OAuth.OAUTH_TOKEN, consumer.getToken());
				edit.putString(OAuth.OAUTH_TOKEN_SECRET,
						consumer.getTokenSecret());
				edit.commit();

				String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
				String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");

				consumer.setTokenWithSecret(token, secret);

				// redirect to Setting Activity
				Intent intent = new Intent(context, Setting.class);
				intent.putExtra("TYPE", R.string.REGISTER);
				intent.putExtra("ACCOUNT", CocoikoConstains.TWITTER);
				context.startActivity(intent);
				finish();

				Log.i(TAG, "OAuth - Access Token Retrieved");

			} catch (Exception e) {
				Log.e(TAG, "OAuth - Access Token Retrieval Error", e);
			}

			return null;
		}

	}

}
